package vn.edu.uit.chemistry;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.UnknownHostException;

import vn.edu.uit.chemistry.utilities.TCPClient;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class NhanKetQua extends Activity {

	TextView tvTitle;
	TextView tvDiem;
	ProgressBar prDoiDiem;
	ImageView imgNhanFile;

	String kind = "";
	String nameFile = "";
	String sizeFile = "";
	String sender = "";

	TextView tvFile;
	TextView tvSize;
	TextView tvSender;
	TextView tvPercent;
	ProgressBar prPercent;

	String dapanHS = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_nhan_dap_an);

		tvTitle = (TextView) findViewById(R.id.tvTitle);

		Intent startIntent = getIntent();
		if (startIntent != null) {
			Bundle b = startIntent.getExtras();
			dapanHS = b.getString("dapanHS");
		}

		new SendResultAsyncTask().execute();

		SharedPreferences prefs = getSharedPreferences("FILENHAN", 0);
		kind = prefs.getString("kind", "");

		SharedPreferences.Editor editor = prefs.edit();
		editor.putString("name", nameFile);
		editor.putString("size", sizeFile);
		editor.putString("sender", sender);
		editor.putInt("percent", 0);
		editor.commit();

		if (kind.equals("BKT15")) {
			tvTitle.setText("Kết quả kiểm tra 15 phút");
		} else if (kind.equals("BKT45")) {
			tvTitle.setText("Kết quả kiểm tra 45 phút");
		}

		tvDiem = (TextView) findViewById(R.id.tvDiem);
		tvDiem.postDelayed(onEverySecondDiem, 0);

		prDoiDiem = (ProgressBar) findViewById(R.id.prDoiDiem);
		imgNhanFile = (ImageView) findViewById(R.id.imgNhanFile);

		tvFile = (TextView) findViewById(R.id.tvFile);
		tvSize = (TextView) findViewById(R.id.tvSize);
		tvSender = (TextView) findViewById(R.id.tvSender);
		tvPercent = (TextView) findViewById(R.id.tvPercent);

		prPercent = (ProgressBar) findViewById(R.id.prPercent);
		imgNhanFile.postDelayed(onEverySecondDA, 0);
	}
	
	final class SendResultAsyncTask extends AsyncTask<Void, Void, Void>{

		public SendResultAsyncTask() {
			
		}
		
		@Override
		protected Void doInBackground(Void... params) {
			SharedPreferences prefs = getSharedPreferences("TaiKhoanGV", 0);
			String ipGV = prefs.getString("ip", "").toString();
			String portGV = prefs.getString("port", "").toString();

			prefs = getSharedPreferences("TaiKhoanHS", 0);
			String tenHS = prefs.getString("hoten", "").toString();
			String mshs = prefs.getString("mshs", "").toString();
			String ipHS = prefs.getString("ip", "").toString();

			try {
				TCPClient client = new TCPClient(getApplicationContext(), ipGV,
						Integer.parseInt(portGV));
				client.nopBaiKT15(tenHS, mshs, ipHS, dapanHS);
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}

	public Runnable onEverySecondDiem = new Runnable() {
		public void run() {
			new DiemAsyncTask().execute();
		}
	};

	public Runnable onEverySecondDA = new Runnable() {
		public void run() {
			new DAAsyncTask().execute();
		}
	};

	final class DiemAsyncTask extends AsyncTask<Void, Void, Void> {

		private String dapanGV = "";

		public DiemAsyncTask() {
		}

		@Override
		protected Void doInBackground(Void... params) {
			SharedPreferences prefs = getSharedPreferences("ChamDiem", 0);
			dapanGV = prefs.getString("dapanGV", "");
			return null;
		}

		@Override
		protected void onPostExecute(final Void unused) {
			if (!dapanGV.equals("")) {
				int soCauDung = 0;
				int diem = 0;
				dapanHS = dapanHS.toUpperCase();
				
				for (int i = 0; i < dapanGV.length(); i++) {
					if (dapanHS.codePointAt(i) == dapanGV.codePointAt(i)) {
						soCauDung++;
					}
				}
				
				diem = soCauDung * 10 / 15;
				if (diem < 4) {
					diem += 1;
				}
				
				tvDiem.setText("" + diem);
				prDoiDiem.setVisibility(View.GONE);
				tvDiem.removeCallbacks(onEverySecondDiem);
				
				File sdcard = Environment.getExternalStorageDirectory().getAbsoluteFile();
				File file = new File(sdcard,"/hoa hoc/kiem tra/kt15/dapanGV.txt");

				FileOutputStream fos;
				byte[] data = new String("GV-"+dapanGV+"\nHS-"+dapanHS).getBytes();
				try {
					fos = new FileOutputStream(file);
					fos.write(data);
					fos.flush();
					fos.close();
				} catch (FileNotFoundException e) {
					// handle exception
				} catch (IOException e) {
					// handle exception
				}
				
			} else {
				tvDiem.postDelayed(onEverySecondDiem, 0);
			}
		}
	}

	final class DAAsyncTask extends AsyncTask<Void, Void, Void> {

		String name = "";
		String size = "";
		String sender = "";

		private int percent = 0;

		public DAAsyncTask() {
		}

		@Override
		protected Void doInBackground(Void... params) {
			SharedPreferences prefs = getSharedPreferences("FILENHAN", 0);
			name = prefs.getString("name", "");
			size = prefs.getString("size", "");
			sender = prefs.getString("sender", "");
			percent = prefs.getInt("percent", 0);

			return null;
		}

		@Override
		protected void onPostExecute(final Void unused) {
			tvFile.setText(name);
			tvSize.setText(size + " bytes");
			tvSender.setText(sender);

			tvPercent.setText(percent + " %");
			prPercent.setProgress(percent);
			if (percent < 100) {
				imgNhanFile.postDelayed(onEverySecondDA, 0);
			} else {
				imgNhanFile.removeCallbacks(onEverySecondDA);
//				Toast.makeText(getApplicationContext(),
//						"Đã nhận đáp án thành công.", Toast.LENGTH_SHORT)
//						.show();
				finish();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			return false;
		}
		return false;
	}

}
